package com.zzj.bill.service.impl;

import com.zzj.bill.domain.IdGeneratorEntity;
import com.zzj.bill.mapper.GeneratorMapper;
import com.zzj.bill.service.GeneratorService;
import com.zzj.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author zengZhiJun
 * @create 2022/1/24 16:30
 */

@Service("GeneratorService")
public class GeneratorServiceImpl implements GeneratorService {

    @Resource
    private GeneratorMapper generatorMapper;

    @Override
    public IdGeneratorEntity findOne(String sequence) {
        return  generatorMapper.selectIdGeneratorBySequenceName(sequence);
    }

    @Override
    public void saveAndFlush(IdGeneratorEntity generator) {
        generatorMapper.insertIdGenerator(generator);
    }

    @Override
    public Long generate(String sequence, int count, boolean isNeedChangeDate) {
        IdGeneratorEntity generator = generatorMapper.selectIdGeneratorBySequenceName(sequence);
        Long returnValue;

        int added = count;
        if (added <= 0) {
            // 至少增加一个
            added = 1;
        }
        Date currentDate = new Date();
        if (generator == null) {
            generator = new IdGeneratorEntity();
            generator.setSequenceName(sequence);
            generator.setCurrentGeneratorTime(currentDate);
            returnValue = (long) added;
            generator.setCurrentValue((long) added);
        } else {
            returnValue = generator.getCurrentValue() + added;
            generator.setCurrentValue(returnValue);
        }

        if (isNeedChangeDate) {
            if (!DateUtils.isSameDay(generator.getCurrentGeneratorTime(), currentDate)) {
                returnValue = (long) added;
                generator.setCurrentValue((long) added);
            }
        }
        generator.setCurrentGeneratorTime(currentDate);
        generatorMapper.insertIdGenerator(generator);
        return returnValue;
    }
}
